﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;

namespace Shared.JwtHelper
{
    /// <summary>
    /// JWT 认证
    /// </summary>
    public static class JwtExtensions
    {
        /// <summary>
        /// 添加 Jwt 认证
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwt(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<TokenManagement>(configuration.GetSection("TokenManagement"));
            var tokenManagement = configuration.GetSection("TokenManagement").Get<TokenManagement>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true, //是否验证秘钥
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenManagement.Secret)),
                    ValidIssuer = tokenManagement.Issuer,
                    ValidAudience = tokenManagement.Audience,
                    ValidateIssuer = false,//是否验证发布者
                    ValidateAudience = false, //是否验证接受者
                    ValidateLifetime = true, //是否验证过期时间
                    //ClockSkew默认值为5分钟，它是一个缓冲期，例如Token设置有效期为30分钟，
                    //到了30分钟的时候是不会过期的，会有这么个缓冲时间，也就是35分钟才会过期
                    ClockSkew = TimeSpan.FromMinutes(tokenManagement.RefreshTokenExpiresMinutes)
                };
            });
            return services;
        }
    }
    
    #region 带有刷新Token 的功能
    //public class Token
    //{
    //    public string TokenContent { get; set; }
    //    public DateTime Expires { get; set; }
    //}
    //public enum TokenType
    //{
    //    AccessToken = 1,
    //    RefreshToken = 2
    //}
    //public class ComplexToken
    //{
    //    public Token AccessToken { get; set; }
    //    public Token RefreshToken { get; set; }
    //}
    #endregion

}
